package com.usdt.system.service.impl.cp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usdt.common.core.domain.entity.SysDictData;
import com.usdt.common.core.domain.entity.SysRole;
import com.usdt.common.core.domain.entity.SysUser;
import com.usdt.common.exception.ServiceException;
import com.usdt.common.utils.bean.BeanUtil;
import com.usdt.system.cp.utils.UserAndDeptUtils;
import com.usdt.system.domain.cp.ClueCustomerInfoEntity;
import com.usdt.system.domain.cp.ClueFollowUpEntity;
import com.usdt.system.domain.cp.ClueRegisterEntity;
import com.usdt.system.domain.req.BatchTransferOutReqVO;
import com.usdt.system.domain.req.ClueCustomerInfoReqVO;
import com.usdt.system.domain.req.ClueFollowUpReqVO;
import com.usdt.system.domain.req.ClueRegisterListExportReqVO;
import com.usdt.system.domain.req.ClueRegisterReqVO;
import com.usdt.system.domain.req.ClueRegisterUpdateReqVO;
import com.usdt.system.domain.resp.BatchClueRespVO;
import com.usdt.system.domain.resp.ClueCustomerInfoRespVO;
import com.usdt.system.domain.resp.ClueFollowUpRespVO;
import com.usdt.system.domain.resp.ClueRegisterListRespVO;
import com.usdt.system.domain.resp.ClueRegisterRespVO;
import com.usdt.system.domain.resp.ProjectScopRespVO;
import com.usdt.system.domain.resp.SalespersonRespVO;
import com.usdt.system.dto.cp.ClueRegisterListExcelDTO;
import com.usdt.system.mapper.cp.ClueRegisterMapper;
import com.usdt.system.service.ISysDictTypeService;
import com.usdt.system.service.ISysUserService;
import com.usdt.system.service.cp.ClueCustomerInfoService;
import com.usdt.system.service.cp.ClueFollowUpService;
import com.usdt.system.service.cp.ClueRegisterService;

/**
 * <p>
 * 线索登记 服务实现类
 * </p>
 *
 * @author L
 * @since 2025-09-29
 */
@Service
public class ClueRegisterServiceImpl extends ServiceImpl<ClueRegisterMapper, ClueRegisterEntity> implements ClueRegisterService {
	
	private static final Integer Sales_Manager_Id = 100;
	private static final Integer Sales_Person_Id = 101;
	
	@Value("${sys.properties.ky.main_dept_id}")
	public String mainDeptId;
	
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private ClueCustomerInfoService clueCustomerInfoService;
    
	@Autowired
    private ClueFollowUpService clueFollowUpService;
    
    @Autowired
    private ISysDictTypeService dictTypeService;
    
	@Override
	public List<SalespersonRespVO> salesperson() {
		List<SalespersonRespVO> result = new ArrayList<SalespersonRespVO>();
		List<SysUser> userList = userService.getUserListByRoleId(Sales_Person_Id);
		List<SysDictData> projectData = dictTypeService.selectDictDataByType("project_manage");
		String currentDeptId = this.getCurrentDeptId();
		if(!CollectionUtils.isEmpty(userList)) {
			for (SysUser sysUser : userList) {
				List<String> asList = Arrays.asList(sysUser.getCpDeptId().split(","));
				if(null==currentDeptId) {
					for (String deptId : asList) {
						SalespersonRespVO respVO = new SalespersonRespVO();
						SysDictData project = projectData.stream().filter(e->deptId.equals(e.getDictValue())).findAny().orElse(null);
						respVO.setUserId(sysUser.getCpUserid());
						respVO.setUserName(sysUser.getNickName());
						respVO.setDeptId(deptId);
						respVO.setDeptName(project.getDictLabel());
						result.add(respVO);
					}
				}else {
					for (String deptId : asList) {
						if(currentDeptId.equals(deptId)) {
							SalespersonRespVO respVO = new SalespersonRespVO();
							SysDictData project = projectData.stream().filter(e->deptId.equals(e.getDictValue())).findAny().orElse(null);
							respVO.setUserId(sysUser.getCpUserid());
							respVO.setUserName(sysUser.getNickName());
							respVO.setDeptId(deptId);
							respVO.setDeptName(project.getDictLabel());
							result.add(respVO);
						}
					}
				}
			}
		}
		return result;
	}
	
	@Override
	public List<ProjectScopRespVO> projectScop() {
		List<ProjectScopRespVO> result = new ArrayList<ProjectScopRespVO>();
		
		List<SysDictData> projectData = dictTypeService.selectDictDataByType("project_manage");
		String currentDeptId = UserAndDeptUtils.getCurrentDeptId();
		SysDictData project = projectData.stream().filter(e->currentDeptId.equals(e.getDictValue())).findAny().orElse(null);
		ProjectScopRespVO vo = new ProjectScopRespVO();
		vo.setDeptId(currentDeptId);
		vo.setDeptName(project.getDictLabel()+"(本项目)");
		vo.setIsSelf(true);
		result.add(vo);
		
		SysUser sysUser = userService.selectUserByCpId(UserAndDeptUtils.getCurrentUserId());
		List<String> deptList = Arrays.stream(sysUser.getCpDeptId().split(","))
                .collect(Collectors.toList());
		deptList.remove(currentDeptId);
		if (!CollectionUtils.isEmpty(deptList)) {
			for (String deptId : deptList) {
				SysDictData pro = projectData.stream().filter(e->deptId.equals(e.getDictValue())).findAny().orElse(null);
				ProjectScopRespVO respVo = new ProjectScopRespVO();
				respVo.setDeptId(deptId);
				respVo.setDeptName(pro.getDictLabel());
				result.add(respVo);
			}
		}
		return result;
	}
	
	@Override
	public ClueRegisterRespVO getByPhoneNumber(String keyWord) {
		Map<String, String> currentUserIdAndDeptId = UserAndDeptUtils.getCurrentUserIdAndDeptId();
		
		String currentUserId = currentUserIdAndDeptId.get("currentUserId");
		String currentDeptId = currentUserIdAndDeptId.get("currentDeptId");
		Integer clueId = baseMapper.getByPhoneNumber(keyWord,currentUserId,currentDeptId);
		if(null!=clueId) {
			return this.detail(clueId);
		}
		return null;
	}
    
	@Override
	public IPage<ClueRegisterListRespVO> list(String source, String level, String keyWord, String startDate, String endDate, String userId,
			String visitStatus, Integer pageNum, Integer pageSize){
		
		String currentDeptId = this.getCurrentDeptId();
		String currentUserId = this.getUserId();
		IPage<ClueRegisterListRespVO> page = baseMapper.findPageList(
				new Page<>(pageNum, pageSize),
				source, level, keyWord, startDate, endDate, userId,visitStatus
				,currentDeptId,currentUserId
				);
		return page;
	}

	/** 获取当前人员：是否只查自己
	 * @return
	 */
	private String getUserId() {
		String result = UserAndDeptUtils.getCurrentUserId();
		SysUser sysUser = userService.selectUserByCpId(result);
		List<SysRole> roles = sysUser.getRoles();
		if(!CollectionUtils.isEmpty(roles)) {
			SysRole orElse = roles.stream().filter(e->(Sales_Manager_Id+"").equals(e.getRoleId()+"")).findAny().orElse(null);
			if(null!=orElse) {
				return null;
			}
		}
		return result;
	}

	/** 获取当前部门
	 * @return
	 */
	private String getCurrentDeptId() {
		String currentDeptId = UserAndDeptUtils.getCurrentDeptId();
		if(mainDeptId.equals(currentDeptId)) {
			currentDeptId=null;
		}
		return currentDeptId;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean insert(ClueRegisterReqVO vo) {
		//拆分项目
		String synProjects = vo.getSynProjects();
		List<String> deptList = Arrays.asList(synProjects.split(","));
		for (String deptId : deptList) {
			insertClueRegister(deptId,vo);
		}
		return true;
	}

	/**新增线索登记
	 */
	private void insertClueRegister(String deptId, ClueRegisterReqVO vo) {
		ClueRegisterEntity clueRegisterEntity = BeanUtil.toBean(vo, ClueRegisterEntity.class);
		Map<String, String> currentUserIdAndDeptId = UserAndDeptUtils.getCurrentUserIdAndDeptId();
		
		clueRegisterEntity.setDeptId(deptId);
		clueRegisterEntity.setCreateBy(currentUserIdAndDeptId.get("currentUserId"));
		clueRegisterEntity.setUpdateBy(currentUserIdAndDeptId.get("currentUserId"));
		baseMapper.insert(clueRegisterEntity);
		if(!CollectionUtils.isEmpty(vo.getClueCustomerList())) {
			insertOrUpdateClueCustomerInfoList(clueRegisterEntity.getId(),deptId, vo.getClueCustomerList());
		}
	}

	/**新增或者修改线索客户
	 * @param id
	 * @param clueCustomerList
	 */
	private void insertOrUpdateClueCustomerInfoList(Integer id, String deptId, List<ClueCustomerInfoReqVO> clueCustomerList) {
		List<ClueCustomerInfoEntity> list = new ArrayList<ClueCustomerInfoEntity>(clueCustomerList.size());
		Map<String, String> currentUserIdAndDeptId = UserAndDeptUtils.getCurrentUserIdAndDeptId();
		clueCustomerList.forEach(e->{
			ClueCustomerInfoEntity clueCustomerInfoEntity = BeanUtil.toBean(e, ClueCustomerInfoEntity.class);
			clueCustomerInfoEntity.setClueId(id);
			clueCustomerInfoEntity.setDeptId(deptId);
			clueCustomerInfoEntity.setCreateBy(currentUserIdAndDeptId.get("currentUserId"));
			clueCustomerInfoEntity.setUpdateBy(currentUserIdAndDeptId.get("currentUserId"));
			list.add(clueCustomerInfoEntity);
		});
		
		for (ClueCustomerInfoEntity clueCustomerInfoEntity : list) {
			//根据部门,手机号 查重
			List<ClueCustomerInfoEntity> checkList = clueCustomerInfoService.checkClueCustomerInfoUniqueByDeptIdAndPhoneNumber(deptId,clueCustomerInfoEntity.getPhoneNumber(),clueCustomerInfoEntity.getId());
			if(!CollectionUtils.isEmpty(checkList)) {
				//查询项目
				List<SysDictData> projectData = dictTypeService.selectDictDataByType("project_manage");
				SysDictData project = projectData.stream().filter(e->deptId.equals(e.getDictValue())).findAny().orElse(null);
				throw new ServiceException("该线索在"+project.getDictLabel()+"项目已存在", -1);
			}
			clueCustomerInfoService.saveOrUpdate(clueCustomerInfoEntity);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer update(Integer id,ClueRegisterReqVO vo) {
		ClueRegisterEntity clueRegisterEntity = baseMapper.selectById(id);
		BeanUtil.copyProperties(vo, clueRegisterEntity);
		clueRegisterEntity.setUpdateBy(UserAndDeptUtils.getCurrentUserIdAndDeptId().get("currentUserId"));
		baseMapper.updateById(clueRegisterEntity);
		
		//删除
		clueCustomerInfoService.delByClueId(id);
		if(!CollectionUtils.isEmpty(vo.getClueCustomerList())) {
			insertOrUpdateClueCustomerInfoList(id,clueRegisterEntity.getDeptId(), vo.getClueCustomerList());
		}
		return id;
	}

	@Override
	public ClueRegisterRespVO detail(Integer id) {
		ClueRegisterEntity clueRegisterEntity = baseMapper.selectById(id);
		ClueRegisterRespVO clueRegisterRespVO = BeanUtil.toBean(clueRegisterEntity, ClueRegisterRespVO.class);
		
		//线索人员
		List<ClueCustomerInfoEntity> clueCustomerInfoEntityList =  clueCustomerInfoService.getClueCustomerInfoByClueId(id);
		if(!CollectionUtils.isEmpty(clueCustomerInfoEntityList)) {
			clueRegisterRespVO.setClueCustomerList(BeanUtil.toBeans(clueCustomerInfoEntityList, ClueCustomerInfoRespVO.class));
		}
		
		//跟进记录
		List<ClueFollowUpEntity> clueFollowUpList = clueFollowUpService.getClueFollowUpByClueId(id);
		if(!CollectionUtils.isEmpty(clueFollowUpList)) {
			for (ClueFollowUpEntity clueFollowUp : clueFollowUpList) {
				SysUser sysUser = userService.selectUserByCpId(clueFollowUp.getCreateBy());
				clueFollowUp.setCreateByName(sysUser.getNickName());
			}
			clueRegisterRespVO.setClueFollowUpList(BeanUtil.toBeans(clueFollowUpList, ClueFollowUpRespVO.class));
		}
		
		//当前业务员
		SysUser sysUser = userService.selectUserByCpId(clueRegisterEntity.getCreateBy());
		clueRegisterRespVO.setCurrentUserName(sysUser.getNickName());
		clueRegisterRespVO.setCurrentUserId(sysUser.getCpUserid());
		return clueRegisterRespVO;
	}

	@Override
	public Integer updateLevel(Integer id, ClueRegisterUpdateReqVO vo) {
		ClueRegisterEntity clueRegisterEntity = baseMapper.selectById(id);
		clueRegisterEntity.setLevel(vo.getLevel());
		clueRegisterEntity.setUpdateBy(UserAndDeptUtils.getCurrentUserIdAndDeptId().get("currentUserId"));
		
		baseMapper.updateById(clueRegisterEntity);
		return id;
	}

	@Override
	public Integer updateVisitTatus(Integer id, ClueRegisterUpdateReqVO vo) {
		ClueRegisterEntity clueRegisterEntity = baseMapper.selectById(id);
		clueRegisterEntity.setVisitStatus(vo.getVisitTatus());
		clueRegisterEntity.setUpdateBy(UserAndDeptUtils.getCurrentUserIdAndDeptId().get("currentUserId"));
		
		baseMapper.updateById(clueRegisterEntity);
		return id;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer transferOut(Integer id, ClueRegisterUpdateReqVO vo) {
		ClueRegisterEntity clueRegisterEntity = baseMapper.selectById(id);
		clueRegisterEntity.setCreateBy(vo.getOutUserId());
		clueRegisterEntity.setDeptId(vo.getOutDeptId());
		clueRegisterEntity.setUpdateBy(UserAndDeptUtils.getCurrentUserIdAndDeptId().get("currentUserId"));
		baseMapper.updateById(clueRegisterEntity);
		
		clueCustomerInfoService.transferOut(id,vo.getOutUserId(),vo.getOutDeptId(),UserAndDeptUtils.getCurrentUserIdAndDeptId().get("currentUserId"));
		return id;
	}

	@Override
	public Integer followUp(Integer id, ClueFollowUpReqVO vo) {
		Map<String, String> currentUserIdAndDeptId = UserAndDeptUtils.getCurrentUserIdAndDeptId();
		ClueFollowUpEntity clueFollowUpEntity = BeanUtil.toBean(vo, ClueFollowUpEntity.class);
		clueFollowUpEntity.setClueId(id);
		clueFollowUpEntity.setCreateBy(currentUserIdAndDeptId.get("currentUserId"));
		clueFollowUpEntity.setUpdateBy(currentUserIdAndDeptId.get("currentUserId"));
		clueFollowUpService.save(clueFollowUpEntity);
		
		return clueFollowUpEntity.getId();
	}

	@Override
	public List<ClueRegisterListExcelDTO> listExport(ClueRegisterListExportReqVO vo) {
		String currentDeptId = this.getCurrentDeptId();
		String currentUserId = this.getUserId();
		List<ClueRegisterListRespVO> list = baseMapper.findList(
				vo.getSource(), 
				vo.getLevel(), 
				vo.getKeyWord(), 
				vo.getStartDate(), 
				vo.getEndDate(), 
				vo.getUserId(),
				vo.getVisitStatus(),
				currentDeptId,
				currentUserId);
		
		return CollectionUtils.isEmpty(list)?new ArrayList<ClueRegisterListExcelDTO>():BeanUtil.toBeans(list, ClueRegisterListExcelDTO.class);
	}

	@Override
	public List<BatchClueRespVO> getBatchClueByPhoneNumber(String phoneNumber,List<String> deptIds) {
		
		return baseMapper.getBatchClueByPhoneNumber(phoneNumber,deptIds);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean batchTransferOut(BatchTransferOutReqVO vo) {
		List<Integer> ids = vo.getIds();
		if(CollectionUtils.isEmpty(vo.getIds())){
			QueryWrapper<ClueRegisterEntity> query = new QueryWrapper<ClueRegisterEntity>();
			query.eq("dept_id", vo.getFromDeptId()).eq("create_by", vo.getFromUserId()).eq("is_del", false);
			List<ClueRegisterEntity> clueList = baseMapper.selectList(query );
			if(!CollectionUtils.isEmpty(clueList)) {
				ids = clueList.stream().map(e->e.getId()).toList();
			}
		}
		if(!CollectionUtils.isEmpty(ids)) {
			ClueRegisterEntity clueRegisterEntity = new ClueRegisterEntity();
			clueRegisterEntity.setDeptId(vo.getOutDeptId());
			clueRegisterEntity.setCreateBy(vo.getOutUserId());
			clueRegisterEntity.setUpdateBy(UserAndDeptUtils.getCurrentUserId());
			
			QueryWrapper<ClueRegisterEntity> q = new QueryWrapper<ClueRegisterEntity>();
			q.in("id", ids);
			baseMapper.update(clueRegisterEntity, q);
			clueCustomerInfoService.batchTransferOut(ids,vo.getOutUserId(),vo.getOutDeptId());
		}
		return true;
	}

	@Override
	public IPage<BatchClueRespVO> batchClueTransferOutPage(List<String> sourceList, String userId, List<String> deptIds,String phoneNumber, Integer pageNum,
			Integer pageSize) {
		
		return baseMapper.batchClueTransferOutPage(
				new Page<>(pageNum, pageSize),
				sourceList, userId, deptIds,phoneNumber
				);
	}
}
